<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MetaMask 连接测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            max-width: 600px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }
        
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        .test-item {
            background: #f8f9fa;
            padding: 20px;
            margin-bottom: 15px;
            border-radius: 10px;
            border-left: 4px solid #ccc;
        }
        
        .test-item.success {
            border-left-color: #28a745;
            background: #d4edda;
        }
        
        .test-item.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        
        .test-item.warning {
            border-left-color: #ffc107;
            background: #fff3cd;
        }
        
        .test-item h3 {
            font-size: 16px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .test-item p {
            font-size: 14px;
            color: #555;
            margin: 5px 0;
        }
        
        .icon {
            font-size: 20px;
        }
        
        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
            transition: all 0.3s;
        }
        
        button:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        code {
            background: #eee;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }
        
        .summary {
            margin-top: 30px;
            padding: 20px;
            background: #e7f3ff;
            border-radius: 10px;
            border-left: 4px solid #0066cc;
        }
        
        .summary h3 {
            color: #0066cc;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 MetaMask 连接测试</h1>
        <p class="subtitle">此页面会测试 MetaMask 连接的各个环节，帮助诊断问题</p>
        
        <div id="results"></div>
        
        <button id="testBtn" onclick="runTests()">开始测试</button>
        
        <div id="summary" style="display: none;" class="summary">
            <h3>📊 测试总结</h3>
            <p id="summaryText"></p>
        </div>
    </div>
    
    <script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"></script>
    <script>
        const contractAddress = "0x5FbDB2315678afecb367f032d93F642f64180aa3";
        const expectedChainId = 31337; // Hardhat
        const results = [];
        
        function addResult(title, status, message, details = null) {
            results.push({ title, status, message, details });
            renderResults();
        }
        
        function renderResults() {
            const container = document.getElementById('results');
            container.innerHTML = results.map(r => `
                <div class="test-item ${r.status}">
                    <h3>
                        <span class="icon">${getIcon(r.status)}</span>
                        ${r.title}
                    </h3>
                    <p>${r.message}</p>
                    ${r.details ? `<p><code>${r.details}</code></p>` : ''}
                </div>
            `).join('');
        }
        
        function getIcon(status) {
            switch(status) {
                case 'success': return '✅';
                case 'error': return '❌';
                case 'warning': return '⚠️';
                default: return '⏳';
            }
        }
        
        async function runTests() {
            const btn = document.getElementById('testBtn');
            btn.disabled = true;
            btn.textContent = '测试中...';
            results.length = 0;
            document.getElementById('summary').style.display = 'none';
            
            try {
                // Test 1: MetaMask Installation
                addResult('1. MetaMask 安装检测', 'loading', '检测中...', null);
                await sleep(500);
                
                if (typeof window.ethereum !== 'undefined') {
                    addResult('1. MetaMask 安装检测', 'success', 'MetaMask 已安装', `ethereum对象已找到`);
                } else {
                    addResult('1. MetaMask 安装检测', 'error', 'MetaMask 未安装', '请安装 MetaMask 浏览器扩展');
                    showSummary(false, '请先安装 MetaMask');
                    btn.disabled = false;
                    btn.textContent = '重新测试';
                    return;
                }
                
                // Test 2: Request Accounts
                addResult('2. 账户连接', 'loading', '请求账户权限...', null);
                let accounts;
                try {
                    accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                    if (accounts && accounts.length > 0) {
                        addResult('2. 账户连接', 'success', '账户连接成功', accounts[0]);
                    } else {
                        addResult('2. 账户连接', 'error', '未获取到账户', '请在 MetaMask 中连接账户');
                        showSummary(false, '未连接账户');
                        btn.disabled = false;
                        btn.textContent = '重新测试';
                        return;
                    }
                } catch (error) {
                    addResult('2. 账户连接', 'error', '用户拒绝连接', error.message);
                    showSummary(false, '用户拒绝连接');
                    btn.disabled = false;
                    btn.textContent = '重新测试';
                    return;
                }
                
                // Test 3: Provider Creation
                addResult('3. Provider 创建', 'loading', '创建 Provider...', null);
                await sleep(500);
                
                let provider;
                try {
                    provider = new ethers.providers.Web3Provider(window.ethereum);
                    addResult('3. Provider 创建', 'success', 'Provider 创建成功', 'ethers.js 连接已建立');
                } catch (error) {
                    addResult('3. Provider 创建', 'error', 'Provider 创建失败', error.message);
                    showSummary(false, 'Provider 创建失败');
                    btn.disabled = false;
                    btn.textContent = '重新测试';
                    return;
                }
                
                // Test 4: Network Check
                addResult('4. 网络检测', 'loading', '检测网络...', null);
                await sleep(500);
                
                let network;
                try {
                    network = await provider.getNetwork();
                    const chainId = network.chainId;
                    
                    const networkNames = {
                        1: 'Ethereum Mainnet',
                        31337: 'Hardhat Local',
                        1337: 'Localhost'
                    };
                    
                    const networkName = networkNames[chainId] || `Unknown (${chainId})`;
                    
                    if (chainId === expectedChainId || chainId === 1337) {
                        addResult('4. 网络检测', 'success', `网络正确: ${networkName}`, `链ID: ${chainId}`);
                    } else {
                        addResult('4. 网络检测', 'warning', `网络不匹配: ${networkName}`, `期望链ID: ${expectedChainId}, 当前: ${chainId}`);
                    }
                } catch (error) {
                    addResult('4. 网络检测', 'error', '网络检测失败', error.message);
                }
                
                // Test 5: Signer
                addResult('5. Signer 获取', 'loading', '获取 Signer...', null);
                await sleep(500);
                
                let signer;
                try {
                    signer = provider.getSigner();
                    const address = await signer.getAddress();
                    addResult('5. Signer 获取', 'success', 'Signer 获取成功', address);
                } catch (error) {
                    addResult('5. Signer 获取', 'error', 'Signer 获取失败', error.message);
                    showSummary(false, 'Signer 获取失败');
                    btn.disabled = false;
                    btn.textContent = '重新测试';
                    return;
                }
                
                // Test 6: Contract Connection
                addResult('6. 合约连接', 'loading', '连接合约...', null);
                await sleep(500);
                
                try {
                    // Simple ABI with getContractOwner
                    const simpleABI = [
                        "function getContractOwner() public view returns (address)"
                    ];
                    
                    const contract = new ethers.Contract(contractAddress, simpleABI, signer);
                    addResult('6. 合约连接', 'success', '合约实例创建成功', contractAddress);
                    
                    // Test 7: Contract Call
                    addResult('7. 合约方法调用', 'loading', '调用 getContractOwner()...', null);
                    await sleep(500);
                    
                    try {
                        const owner = await contract.getContractOwner();
                        addResult('7. 合约方法调用', 'success', '合约调用成功', `合约所有者: ${owner}`);
                        showSummary(true, '所有测试通过！');
                    } catch (error) {
                        addResult('7. 合约方法调用', 'error', '合约调用失败', error.message);
                        showSummary(false, '合约调用失败，可能是合约未部署或网络不匹配');
                    }
                } catch (error) {
                    addResult('6. 合约连接', 'error', '合约连接失败', error.message);
                    showSummary(false, '合约连接失败');
                }
                
            } catch (error) {
                addResult('未知错误', 'error', '测试过程中出现未知错误', error.message);
                showSummary(false, '测试失败');
            }
            
            btn.disabled = false;
            btn.textContent = '重新测试';
        }
        
        function showSummary(success, message) {
            const summary = document.getElementById('summary');
            const summaryText = document.getElementById('summaryText');
            summary.style.display = 'block';
            
            if (success) {
                summaryText.innerHTML = `
                    ✅ <strong>恭喜！</strong> ${message}<br>
                    您的 MetaMask 连接配置完全正常，可以正常使用系统。
                `;
            } else {
                summaryText.innerHTML = `
                    ❌ <strong>检测到问题：</strong> ${message}<br>
                    请查看上面的测试结果，根据失败的步骤进行排查。<br>
                    📖 参考 <a href="./METAMASK_QUICK_FIX.md" target="_blank">快速修复指南</a>
                `;
            }
        }
        
        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }
    </script>
</body>
</html>

